﻿using ASP_MVVC.Data;
using ASP_MVVC.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.EntityFrameworkCore;

namespace ASP_MVVC.Controllers
{

    [ApiController]
    [Route("api/[controller]")]

    public class InvoicesController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public InvoicesController(ApplicationDbContext context)
        {
            _context = context;
        }

        // 上传发票
        [HttpPost("upload")]
        public async Task<IActionResult> UploadInvoice(IFormFile file, [FromForm] string category, [FromForm] decimal amount)
        {
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", file.FileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            var invoice = new Invoices
            {
                Category = category,
                Amount = amount,
                ImagePath = filePath
            };

            _context.Invoices.Add(invoice);
            await _context.SaveChangesAsync();

            return Ok(new { Message = "Invoice uploaded successfully", InvoiceId = invoice.Id });
        }


        // 下载发票图片
        [HttpGet("download/{id}")]
        public async Task<IActionResult> DownloadInvoice(int id)
        {
            var invoice = await _context.Invoices.FindAsync(id);
            if (invoice == null)
            {
                return NotFound();
            }

            var memory = new MemoryStream();
            using (var stream = new FileStream(invoice.ImagePath, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            return File(memory, GetContentType(invoice.ImagePath), Path.GetFileName(invoice.ImagePath));
        }
        InvoiceManagementDbContext db = new InvoiceManagementDbContext();
        // 获取总金额
        [HttpGet("total")]
        public async Task<IActionResult> GetTotalAmount()
        {
            // 使用LINQ查询来计算Amount的总和
            var totalAmount = db.Invoices.Sum(i => i.Amount);

            // 将总和存储在ViewBag中，以便在视图中访问
            

            
            return Ok(new { TotalAmount = totalAmount });
        }

        private string GetContentType(string path)
        {
            var provider = new FileExtensionContentTypeProvider();
            string contentType;
            if (!provider.TryGetContentType(path, out contentType))
            {
                contentType = "application/octet-stream";
            }
            return contentType;
        }


    }
}
